package com.ms.game.utils.actionblocker;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import redis.clients.jedis.Jedis;

import com.ms.service.db.jedis.JedisManager;
import com.ms.service.db.jedis.RedisResourceName;

/**
 * 行為阻擋者
 * @author TW16028
 *
 */
public class ActionBlocker {
	private static final Log log = LogFactory.getLog(ActionBlocker.class);
	
	private static String FIRST_TIME = "1";
	
	/**
	 * 
	 * @param blockType
	 * @param uniqueKey
	 * @return
	 */
	public static boolean checkAndBlock(ActionBlockType blockType, String uniqueKey) {
		Jedis jedis = JedisManager.getResource(RedisResourceName.BLOCKER);
		try {
			String key = blockType.getBlockKey(uniqueKey);
			long result = jedis.setnx(key, FIRST_TIME);
			if (result == 1) {
				jedis.pexpire(key, blockType.getInterval());
				return true;
			} else {
				// 如果不是1
				long count = jedis.incr(key);
				if (count > blockType.getMaxTry()) {
					if (log.isErrorEnabled()) {
						log.error(blockType.name() + " try " + count + " times, player is " + uniqueKey);
					}
				}
				return false;
			}
		}
		catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error(e);
			}
			return false;
		}
		finally {
			if (jedis != null) {
				JedisManager.returnResource(RedisResourceName.BLOCKER, jedis);
			}
		}
	}	
}
